local skynet = require "skynet"
local s = require "service"
local runconfig = require "runconfig"
local CMD = require "game_cmd"
local common = require "scene_common"

local mynode = skynet.getenv("node")

s.snode = nil -- scene_node
s.sname = nil -- scene_id

local function random_scene()
    -- 选择node
    local nodes = {}
    for i, v in pairs(runconfig.scene) do
        table.insert(nodes, i)
        if runconfig.scene[mynode] then
            table.insert(nodes, mynode)
        end
    end
    local idx = math.random(1, #nodes)
    local scenenode = nodes[idx]
    -- 具体场景
    local scenelist = runconfig.scene[scenenode]
    local idx = math.random(1, #scenelist)
    local sceneid = scenelist[idx]
    return scenenode, sceneid
end

s.client.enter = function(msg)
    local msg_ret = {
        cmd = CMD.SERVER_ENTER,
        status = 1,
        msg = "进入scene成功"
    }

    if s.sname then
        msg_ret.status = -1
        msg_ret.msg = "已在场景"
        return msg_ret, CMD.SERVER_ENTER
    end
    local snode, sid = random_scene()
    local sname = "scene" .. sid
    local isok = s.call(snode, sname, "enter", s.id, mynode, skynet.self())
    if not isok then
        msg_ret.status = -1
        msg_ret.msg = "进入失败"
        return msg_ret, CMD.SERVER_ENTER
    end
    s.snode = snode
    s.sname = sname
    -- return msg_ret, CMD.SERVER_ENTER
end

s.client.leave = function(msg)
    if not s.name then
        return {"exit", 1, "没有在场景，不能退出场景"}
    end
    s.leave_scene()
end

-- 改变方向
s.client.shift = function(msg)
    if not s.sname then
        return
    end
    local x = msg[2] or 0
    local y = msg[3] or 0
    s.call(s.snode, s.sname, "shift", s.id, x, y)
end

s.client.move = function(msg)
    if not s.sname then
        return
    end

    local direction = msg.direction
    skynet.error(string.format("移动请求, player_id:%d, direction:%s", s.id, direction))
    direction = math.tointeger(direction)
    if not direction then
        skynet.error("方向参数非法", direction)
        return false
    end

    if direction <= common.Direction.START and direction >= common.Direction.END then
        skynet.error("方向参数非法", direction)
        return false
    end

    s.call(s.snode, s.sname, "move", s.id, direction)
end

s.client.stop_move = function(msg)
    if not s.sname then
        return
    end

    s.call(s.snode, s.sname, "stop_move", s.id)
end

s.leave_scene = function()
    -- 不在场景
    if not s.sname then
        return
    end
    s.call(s.snode, s.sname, "leave", s.id)
    s.snode = nil
    s.sname = nil
end
